#!/usr/bin/env bash
set -euo pipefail

# gen_from_schema generates classes from schema.dart for every used language
# (Dart, Swift, Kotlin/Java) in the appropriate directory.

cd "$(dirname "$0")" || exit

schema="./schema.dart"
patrol_package="./packages/patrol"
patrol_devtools_extension_package="./packages/patrol_devtools_extension"
patrol_dart_out_dir="lib/src/platform/contracts"
patrol_dart_web_out_dir="lib/src/platform/web"

darwin_out="$patrol_package/darwin/Classes/AutomatorServer"
dart_out="$patrol_package/$patrol_dart_out_dir"

android_out="$patrol_package/android/src/main/kotlin/pl/leancode/patrol/contracts"
android_package="pl.leancode.patrol.contracts"

dart run packages/patrol_gen/bin/main.dart "$schema" "$dart_out" "$darwin_out" "$android_out" "$android_package"

pushd "${patrol_package}"

dart fix --apply "$patrol_dart_out_dir"
dart format "$patrol_dart_out_dir"

dart run build_runner build --delete-conflicting-outputs --build-filter="$patrol_dart_out_dir/contracts.g.dart" --build-filter="$patrol_dart_web_out_dir/*.g.dart"

popd

# TODO: We should use necessary contracts in extension
cp "$dart_out/contracts.dart" "$patrol_devtools_extension_package/lib/api/contracts.dart"
cp "$dart_out/contracts.g.dart" "$patrol_devtools_extension_package/lib/api/contracts.g.dart"

dart fix --apply "$patrol_devtools_extension_package"
